// ✅ frontend/router/index.js
// 使用新的路由初始化方式
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from "../stores/user"

// 统一登录中心配置
const UNIFIED_LOGIN_URL = import.meta.env.VITE_UNIFIED_LOGIN_URL || 'https://gf-net.cn/auth'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '待办事项' }
  },
  {
    path: '/todo/:taskNum',
    name: 'TodoDetail',
    component: () => import('../views/TodoDetail.vue'),
    meta: { title: '待办详情' }
  },
  {
    path: '/add',
    name: 'AddTodo',
    component: () => import('../views/AddTodo.vue'),
    meta: { title: '新建待办' }
  }
]

function initRouter() {
  const router = createRouter({
    history: createWebHistory('/todo_mobile/'),
    routes
  })

  // 保存用户认证信息
  function saveUserAuth(userStore, data) {
    userStore.setToken(data.token)
    userStore.setSign(data.sign || '')
    userStore.setUserInfo(data.userInfo)
    userStore.setUsername(data.userInfo.username)
    userStore.setUserDbId(data.userInfo.userDbId)
    userStore.setIsLogin(true)
  }

  // 清理用户认证信息
  function clearUserAuth(userStore) {
    userStore.clearToken()
    userStore.clearSign()
    userStore.clearUserInfo()
    userStore.clearLoginToken()
    userStore.setIsLogin(false)
  }

  // 获取回调URL
  async function getCallbackUrl() {
    const currentUrl = window.location.href
    const url = new URL(currentUrl)
    const basePath = url.origin + url.pathname
    const filename = url.searchParams.get("filename") || ""
    
    const fullCallbackUrl = filename
      ? `${basePath}?filename=${encodeURIComponent(filename)}`
      : basePath

    console.log("🎯 filename:", filename)
    console.log("🎯 最终跳转链接:", fullCallbackUrl)
    
    return fullCallbackUrl
  }

  // 重定向到登录中心
  function redirectToLogin(callback, error = "") {
    const encodedCallback = encodeURIComponent(callback)
    const loginUrl = `${UNIFIED_LOGIN_URL}?callback=${encodedCallback}${error ? `&error=${error}` : ""}`
    window.location.href = loginUrl
  }

  // 路由守卫
  router.beforeEach(async (to, from, next) => {
    console.log('[Router] 路由跳转:', from.path, '->', to.path)
    console.log('[Router] 目标路由:', to.name)
    
    // 设置页面标题
    document.title = to.meta.title || '待办事项'
    
    const userStore = useUserStore()
    
    // 检查是否已登录
    if (userStore.isLogin && userStore.token) {
      console.log('[Router] 用户已登录，继续访问')
      return next()
    }

    // 检查URL参数中是否有access_token
    const urlParams = new URLSearchParams(window.location.search)
    const accessToken = urlParams.get('access_token')
    
    if (accessToken) {
      console.log('[Router] 检测到access_token，开始认证流程...')
      try {
        // 调用认证API
        const res = await fetch("/todo_mobile/api/login", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        })

        const data = await res.json()
        
        if (res.ok && data.token) {
          console.log('[Router] 认证成功，保存用户信息')
          saveUserAuth(userStore, data)
          
          // 清理URL中的access_token参数并跳转
          const cleanedPath = to.path
          const query = { ...to.query }
          delete query.access_token
          console.log('[Router] 清理URL参数并跳转到:', cleanedPath)
          
          return next({ path: cleanedPath, query })
        } else {
          console.error('[Router] 认证失败:', data.message)
          clearUserAuth(userStore)
          const systemURL = await getCallbackUrl()
          return redirectToLogin(systemURL, data.message || "认证失败")
        }
      } catch (error) {
        console.error('[Router] 认证请求失败:', error)
        clearUserAuth(userStore)
        const systemURL = await getCallbackUrl()
        return redirectToLogin(systemURL, "认证服务异常")
      }
    }

    // 没有access_token，重定向到统一登录中心
    console.log('[Router] 未登录，跳转到统一登录中心')
    const systemURL = await getCallbackUrl()
    clearUserAuth(userStore)
    return redirectToLogin(systemURL, "请先登录")
  })

  return router
}

// 创建并导出路由实例
const router = initRouter()

export default router
